package ptumall.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ptumall.model.User;
import ptumall.service.UserService;
import ptumall.utils.JWTUtils;
import ptumall.utils.Result;
import ptumall.utils.ResultCodeEnum;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "1-用户接口")
@RestController
@RequestMapping("/user") //127.0.0.1:8080/user/
public class UserController {
    //依赖注入
    @Autowired
    private UserService userService;
    //注册接口
    @ApiOperation("用户注册")
    @PostMapping("/register") //127.0.0.1:8080/user/register
    public Result<User> register(@RequestBody User user) { //json形式参数
        if (userService.registerService(user) != null) {
            return Result.success(user);
        }else {
         return Result.failure(ResultCodeEnum.USER_IS_EXITES);
        }
    }
    @ApiOperation("用户登录")
    @PostMapping("/login") //127.0.0.1:8080/user/login
    public Result login(@RequestBody User user) {
        User userfromjdbc = userService.loginService(user.getUname(), user.getUpassword());
        if (userfromjdbc == null) {
            return Result.failure(ResultCodeEnum.UNAUTHORIZED,"用户名或密码错误!");
        }else {
            String token = JWTUtils.getToken(userfromjdbc.getUaccount(), userfromjdbc.getUname());
            Map<String,String> userMap = new HashMap();
            userMap.put("userId",userfromjdbc.getUaccount());
            userMap.put("userName",userfromjdbc.getUname());
            userMap.put("token",token);
            return Result.success(userMap);
        }
    }
}
